package com.mydroidchat.controllers;

import com.mydroidchat.data.ChatMessage;
import com.mydroidchat.data.ChatSettings;
import com.mydroidchat.views.ChatApplicationView;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashSet;
import java.util.Set;

public class ChatApplicationController extends Controller {
    private ChatSettings chatSettings;
    private static ChatApplicationController instance;
    private ChatApplicationView applicationView;
    private Controller activeController;
    private Set<ChatMessage> chatMessages = new HashSet<ChatMessage>();

    public static ChatApplicationController getInstance() {
        if (instance == null) {
            instance = new ChatApplicationController();
        }
        return instance;
    }
    
    private ChatApplicationController() {
        applicationView = new ChatApplicationView();
        applicationView.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    
    public void init() {
        try {
            FileInputStream fileInputStream = new FileInputStream("chat.properties");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            chatSettings = (ChatSettings) objectInputStream.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (chatSettings == null) {
            setActiveController(LoginController.getInstance());
        }

        applicationView.setVisible(true);

        System.err.println("done");
    }

    public void setActiveController(Controller controller) {
        if (this.activeController == controller) {
            return;
        }
        if (activeController != null) {
            applicationView.remove(activeController.getView());
        }
        this.activeController = controller;
        applicationView.add(activeController.getView(), BorderLayout.CENTER);
        applicationView.validate();
        applicationView.repaint();
        activeController.refresh();
    }

    public ChatSettings getChatSettings() {
        return chatSettings;
    }

    @Override
    public Container getView() {
        return applicationView;
    }
    
    public Frame getWindowView() {
        return applicationView;
    }

    @Override
    public void refresh() {
        //todo
    }

    public Set<ChatMessage> getChatMessages() {
        return chatMessages;
    }
}
